package handlers

import (
	"github.com/gin-gonic/gin"
	"news-cms/models"
	"news-cms/pkg"
	"strconv"
)

func Register(c *gin.Context) {
	tel := c.PostForm("tel")
	password := c.PostForm("password")
	data := models.User{
		Tel:      tel,
		Password: pkg.Str(password),
	}
	if tel == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "字段不能为空",
		})
		return
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "注册失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "注册成功",
	})
	return
}

func Login(c *gin.Context) {
	tel := c.PostForm("tel")
	password := c.PostForm("password")
	data := models.User{
		Tel:      tel,
		Password: pkg.Str(password),
	}
	var user models.User
	models.DB.Where("password = ?", pkg.Str(password))
	//if tel != user.Tel {
	//	c.JSON(200, gin.H{
	//		"code": 400,
	//		"msg":  "账号不存在",
	//	})
	//	return
	//}
	if password != user.Password {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "密码不正确",
		})
		return
	}
	err := models.DB.Find(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "登录失败",
		})
		return
	}
	uid := c.Query("uid")
	token, _ := pkg.TokenHandler(uid)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": token,
	})
	return
}

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	img := c.PostForm("img")
	data := models.News{
		Title:   title,
		Content: content,
		Img:     img,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "发布失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	offset := (page - 1) * size
	var news []models.News
	models.DB.Offset(offset).Limit(size).Find(&news)
	var count int64
	models.DB.Model(&models.News{}).Count(&count)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  news,
		"count": count,
	})
	return
}
